package controllers

import (
	"LoginTemplate/models"
	"LoginTemplate/utils"
	"bytes"
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	_ "image/jpeg"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
	"strings"
	"time"
)

var GlobalUserInfo *models.Staff
var GlobalUserInfo1 *utils.Client1

type BaseController struct {
	beego.Controller
}

type jsonMsgData struct {
	Code    int         `json:"code"`
	Data    interface{} `json:"data"`
	Message interface{} `json:"message"`
}

func init() {
}

func (b *BaseController) IndexHtml() {
	b.TplName = "index.tpl"
}

func (b *BaseController) ShouldBind(receive interface{}) error {
	request := b.Ctx.Input.RequestBody
	err := json.Unmarshal(request, receive)
	return err
}

func (b *BaseController) JsonMsg(code int, data interface{}, message interface{}) {
	result := jsonMsgData{
		Code:    code,
		Data:    data,
		Message: message,
	}
	b.Data["json"] = result
	b.ServeJSON()
	b.StopRun()
}

func (b *BaseController) accountExist(account string) bool {
	var accountCount int64
	models.DB.Table("staff").
		Where("account = ?", account).Count(&accountCount)
	if accountCount == 0 {
		return false
	} else {
		return true
	}
}

func (b *BaseController) stringArrayDuplicateData(datas []string) (string, int) {
	for i := 0; i < len(datas); i++ {
		var dupNum int = 0
		dupStr := ""
		for j := i + 1; j < len(datas); j++ {
			if datas[i] == datas[j] {
				dupNum += 1
				dupStr = datas[j]
			}
		}
		if dupNum >= 1 {
			return dupStr, dupNum
			break
		}
	}
	return "", 0
}

func (b *BaseController) now() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

func (b *BaseController) structToMap(obj interface{}) map[string]interface{} {
	var data map[string]interface{}
	objByte, _ := json.Marshal(obj)
	_ = json.Unmarshal(objByte, &data)
	return data
}

func (b *BaseController) createDir(path string) {
	_, err := os.Stat(path)
	if os.IsNotExist(err) {
		os.MkdirAll(path, 0775)
	}
}

func (b *BaseController) filterSpecialChar(content string) string {
	keywords := []string{
		"SELECT",
		"INSERT",
		"UPDATE",
		"DELETE",
		"DROP",
		"CREATE",
		"ALTER",
		"FROM",
		"WHERE",
		"AND",
		"OR",
		"EVAL",
		"EXEC",
		"SHELL",
		"select",
		"insert",
		"update",
		"delete",
		"drop",
		"create",
		"alter",
		"from",
		"where",
		"and",
		"or",
		"eval",
		"exec",
		"shell",
		"=",
		"!=",
	}

	// 构建正则表达式，忽略大小写
	regexPattern := fmt.Sprintf("\\b(%s)\\b", strings.Join(keywords, "|"))
	re := regexp.MustCompile(regexPattern)

	// 使用正则表达式替换关键字为空
	filteredInput := re.ReplaceAllStringFunc(content, func(s string) string {
		return strings.Repeat("", len(s)) // 替换为相同长度的 "*"
	})
	filteredInput = strings.Replace(filteredInput, "=", "", -1)
	filteredInput = strings.Replace(filteredInput, "!=", "", -1)
	filteredInput = strings.Replace(filteredInput, "*", "", -1)
	return filteredInput
}

func (b *BaseController) generateRandomString(length int) (string, error) {
	bytes := make([]byte, length)
	_, err := rand.Read(bytes)
	if err != nil {
		return "", err
	}
	return base64.URLEncoding.EncodeToString(bytes), nil
}

func (b *BaseController) sendPostRequest(url string, requestBody []byte) (string, error) {
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(requestBody))
	if err != nil {
		return "", fmt.Errorf("error making POST request: %v", err)
	}
	defer resp.Body.Close()

	responseBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("error reading response: %v", err)
	}

	return string(responseBody), nil
}

/*判断数组中是否含有该字符串*/
func (b *BaseController) containsString(array []string, element string) bool {
	for _, value := range array {
		if value == element {
			return true
		}
	}
	return false
}
